package com.zheng.study.base.bean.search.order;

import com.zheng.study.base.bean.search.SearchEnum;
import com.zheng.study.base.utils.CommonUtil;
import org.springframework.util.Assert;

/**
 * 查询 - 参数 - Order
 * ============================================================================
 * author : fallenpanda
 * createDate:  2018/6/11 。
 * ============================================================================
 */
public class Order {

	private static final String DEFAULT_ORDER_BY  = "createTime";
	private static final SearchEnum.OrderType DEFAULT_ORDER_TYPE = SearchEnum.OrderType.desc;

	private final String orderBy;
	private final SearchEnum.OrderType orderType;

	public Order(String orderBy, SearchEnum.OrderType orderType) {
		this.orderBy = orderBy;
		this.orderType = orderType;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public SearchEnum.OrderType getOrderType() {
		return orderType;
	}

	public static Order order(String orderBy, SearchEnum.OrderType orderType){
		return newBuilder().setOrderBy(orderBy).setOrderType(orderType).build();
	}

	public static Order simpleOrder(){
		return newBuilder().setOrderBy(DEFAULT_ORDER_BY).setOrderType(DEFAULT_ORDER_TYPE).build();
	}

	public static Builder newBuilder(){
		return new Builder();
	}

	public static class Builder{

		private String orderBy;
		private SearchEnum.OrderType orderType;

		public Builder setOrderBy(String orderBy) {
			this.orderBy = orderBy;
			return this;
		}

		public Builder setOrderType(SearchEnum.OrderType orderType) {
			this.orderType = orderType;
			return this;
		}

		public Order build(){
			Assert.hasText(orderBy, "orderBy 不能为空");
			Assert.notNull(orderType, "orderType 不能为空");
			Assert.isTrue(CommonUtil.isField(orderBy), "orderBy 非法参数");
			return new Order(orderBy, orderType);
		}

	}

}
